import json
import configparser
import requests

from PySide2 import QtWidgets, QtCore
from PySide2.QtCore import QFile, QObject, Signal, Qt
from PySide2.QtGui import QIcon, QFont
from PySide2.QtUiTools import QUiLoader
from PySide2.QtWidgets import QApplication, QHeaderView, QToolTip, QAction, QLineEdit

from robotController.binding import original_cash_page, mapping_detail_bind, template_group_bind, check_bind
from robotController import share
from robotController.binding import original_bind, formula_share, original_data_page
from robotController.binding import template_bind
from robotController.binding import mapping_bind
from robotController.binding import menu_bind
from robotController.binding.home_bind import home_bind
from robotController.util import C_Crypto


class MySignals(QObject):
    menu_signal = Signal(int)


class Start:
    def __init__(self):
        qfile_stats = QFile("./static/ui/login.ui")
        qfile_stats.open(QFile.ReadOnly)
        qfile_stats.close()
        # 从UI定义中 创建一个相应的窗口对象
        # 里面的控件对象也成为了对象的属性
        self.lui = QUiLoader().load(qfile_stats)

        self.lui.setFixedSize(self.lui.width(), self.lui.height());
        share.SI.login = self

        self.lui.setWindowTitle("帆博智能RPA机器人")
        appIcon = QIcon("./static/img/logo.ico")
        self.lui.setWindowIcon(appIcon)
        self.lui.setWindowFlags(self.lui.windowFlags() &~ Qt.WindowMinMaxButtonsHint)
        self.lui.widget_2.setStyleSheet('''border-image:url("./static/img/bg.png");''')
        self.lui.widget_5.setStyleSheet('''border-image:url("./static/img/pp.png");''')

        searchAction  = QAction(self.lui.username_lineEdit)
        searchAction.setIcon(QIcon("./static/img/l用户.png"))
        self.lui.username_lineEdit.addAction(searchAction,QLineEdit.LeadingPosition);
        searchAction  = QAction(self.lui.password_lineEdit)
        searchAction.setIcon(QIcon("./static/img/l密码.png"))
        self.lui.password_lineEdit.addAction(searchAction,QLineEdit.LeadingPosition);
        self.lui.login.clicked.connect(lambda: self.login())

        config = configparser.ConfigParser()
        config.read("config.ini")
        flag=config.get("user","flag")
        # 记住密码返回
        if flag == '1':
            username=config.get("user","username")
            password=config.get("user","password")
            self.lui.username_lineEdit.setText(username)
            passwordd = C_Crypto.decodeing(password)
            self.lui.password_lineEdit.setText(passwordd)
            self.lui.memory_checkBox.setChecked(True)


    # 登录
    def login(self):
        try:
            config = configparser.ConfigParser()
            config.read("config.ini")

            url = share.RURL.UAAbackendUrl + "/uaa/oauth/token"
            requests.encoding = 'utf-8'
            uaaParam = {
                "client_id":"c1",
                "client_secret":"secret",
                "grant_type":"password",
                "username":self.lui.username_lineEdit.text(),
                "password":self.lui.password_lineEdit.text()
            }

            result = requests.request(method="POST", url=url,data =uaaParam)
            dataMap = json.loads(result.text)
            # try:
            # 登录成功存储令牌
            share.token.headers = {"Authorization":"Bearer " + dataMap['access_token']}
            share.SI.login.lui.hide()
            p1 = self.lui.password_lineEdit.text()
            self.lui.password_lineEdit.setText('')
            self.mainStart()
            check_flag = self.lui.memory_checkBox.isChecked();
            if check_flag:
                config.set("user","username",self.lui.username_lineEdit.text())
                password = C_Crypto.encoding(p1)
                config.set("user","password",password)
                config.set("user","flag","1")
            else:
                config.set("user","username","")
                config.set("user","password","")
                config.set("user","flag","0")
            config.write(open('config.ini', "w"))
        except Exception as e:
            print(e)
            QtWidgets.QMessageBox.about(self.lui ,"信息提示框", '用户名密码错误')


    def mainStart(self):

        main_data_processing()

        self.ui = share.SI.main.ui

        # 查询组织
        url = share.RURL.backendUrl + "/menu/findByName"
        requests.encoding = 'utf-8'
        result = requests.request(method="GET", url=url, headers=share.token.headers)
        dataMap = json.loads(result.text)
        share.jq.organization = dataMap["data"]["name"]
        self.ui.tit_user.setText("组织名：" + dataMap["data"]["name"])
        self.ui.tit_organization.setText("用户名：" + self.lui.username_lineEdit.text())

        menu_bind.bind()

        # 退出
        self.ui.exit_pushButton.clicked.connect(lambda : self.exit())

        # 源数据窗口事件绑定
        original_bind.bind().incident()
        # 源数据列表事件绑定
        original_data_page.bind()
        original_cash_page.bind()
        # 模板数据窗口事件绑定
        template_bind.bind().incident()

        # 生成对应窗口存留
        mapping_data_processing()
        # 映射绑定
        mapping_bind.bind().incident()
        # 公式编辑绑定
        formula_data_processing()
        # 公式编辑页面组件初始化
        mapping_detail_bind.bind()

        # 分组事件绑定
        template_group_bind.event_bind()

        # 检查窗口初始化
        check_bind.event()

        # 首页下拉框值初始化
        home_bind().ug_comboBox_value_fun()

        # 开启main页面
        self.ui.show()

    def exit(self):
        share.token.headers = {}
        share.SI.main.ui.close()
        share.SI.login.lui.show()

# 加载映射窗口
class mapping_data_processing:
    def __init__(self):
        self.ui = QUiLoader().load("./static/ui/mapping.ui")
        self.ui.setWindowTitle("帆博智能RPA机器人")
        appIcon = QIcon("./static/img/logo.ico")
        self.ui.setWindowIcon(appIcon)
        self.ui.origin_select_lineEdit.setPlaceholderText("源表名称")
        self.ui.template_select_lineEdit.setPlaceholderText("模板表名称")
        self.ui.select_button.clicked.connect(lambda: mapping_bind.bind().create_mapping())
        share.SI.mapping = self
        share.SI.mapping.flag = None

# 加载模板窗口
class formula_data_processing:
    def __init__(self):
        self.ui = QUiLoader().load("./static/ui/template_dispose.ui")
        self.ui.setWindowTitle("帆博智能RPA机器人")
        appIcon = QIcon("./static/img/logo.ico")
        self.ui.setWindowIcon(appIcon)

        self.ui.setWindowFlags(Qt.ToolTip)
        # 设置头
        # 设置单元格平铺表格
        self.ui.formula_tableWidget.setColumnCount(4)
        self.ui.formula_tableWidget.setRowCount(0)
        self.ui.formula_tableWidget.setColumnHidden(0, True);
        self.ui.formula_tableWidget.setHorizontalHeaderLabels(['编号','公司', '公式','操作'])
        self.ui.formula_tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.ui.formula_tableWidget.horizontalHeader().setSectionResizeMode(0, QHeaderView.Interactive)
        self.ui.formula_tableWidget.horizontalHeader().setSectionResizeMode(1, QHeaderView.Interactive)
        self.ui.formula_tableWidget.horizontalHeader().setSectionResizeMode(3, QHeaderView.Interactive)
        self.ui.formula_tableWidget.horizontalHeader().setStyleSheet("QHeaderView::section {background-color:#471EA8;color: #FFFFFF;padding-left: 4px;border: 1px solid #6c6c6c;}")

        # 窗口置顶
        self.ui.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
        self.ui.setWindowFlags(Qt.SubWindow)

        self.ui.close_button.clicked.connect(lambda: flag())

        share.SI.formula = self
        share.SI.formula.flag = None

        def flag():
            formula_share.flag.flag = 0
            share.SI.formula.ui.close()

#  加载主窗口
class main_data_processing:
    def __init__(self):
        self.ui = QUiLoader().load("./static/ui/Main.ui")
        self.ui.showMaximized()
        self.ui.setWindowTitle("帆博智能RPA机器人")
        appIcon = QIcon("./static/img/logo.ico")
        self.ui.setWindowIcon(appIcon)
        self.ui.tit_1.setIcon(QIcon("./static/img/lgi.png"))
        self.ui.tit_2.setIcon(QIcon("./static/img/关于我们.png"))
        self.ui.exit_pushButton.setIcon(QIcon("./static/img/注销.png"))
        self.ui.tit_user.setIcon(QIcon("./static/img/组织.png"))
        self.ui.tit_organization.setIcon(QIcon("./static/img/用户.png"))
        #这种静态的方法设置一个用于显示工具提示的字体。我们使用10px滑体字体。
        QToolTip.setFont(QFont('SansSerif', 10))
        self.ui.tit_2.setToolTip('''软件名称:帆博数字智能机器人
版本号:v1.1.1.0726
许可使用期限:至2022年
版权归属:帆博数字股份有限公司''')
        share.SI.main = self
        share.SI.main.flag = None

app = QApplication([])
start = Start()
start.lui.show()
app.exec_()
